home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / io.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  60.1 KB  |  1,993 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. The io module provides the Python interfaces to stream handling. The
  6. builtin open function is defined in this module.
  7.  
  8. At the top of the I/O hierarchy is the abstract base class IOBase. It
  9. defines the basic interface to a stream. Note, however, that there is no
  10. separation between reading and writing to streams; implementations are
  11. allowed to throw an IOError if they do not support a given operation.
  12.  
  13. Extending IOBase is RawIOBase which deals simply with the reading and
  14. writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
  15. an interface to OS files.
  16.  
  17. BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
  18. subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
  19. streams that are readable, writable, and both respectively.
  20. BufferedRandom provides a buffered interface to random access
  21. streams. BytesIO is a simple stream of in-memory bytes.
  22.  
  23. Another IOBase subclass, TextIOBase, deals with the encoding and decoding
  24. of streams into text. TextIOWrapper, which extends it, is a buffered text
  25. interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
  26. is a in-memory stream for text.
  27.  
  28. Argument names are not part of the specification, and only the arguments
  29. of open() are intended to be used as keyword arguments.
  30.  
  31. data:
  32.  
  33. DEFAULT_BUFFER_SIZE
  34.  
  35.    An int containing the default buffer size used by the module's buffered
  36.    I/O classes. open() uses the file's blksize (as obtained by os.stat) if
  37.    possible.
  38. """
  39. from __future__ import print_function
  40. from __future__ import unicode_literals
  41. __author__ = 'Guido van Rossum <guido@python.org>, Mike Verdone <mike.verdone@gmail.com>, Mark Russell <mark.russell@zen.co.uk>'
  42. __all__ = [
  43.     'BlockingIOError',
  44.     'open',
  45.     'IOBase',
  46.     'RawIOBase',
  47.     'FileIO',
  48.     'BytesIO',
  49.     'StringIO',
  50.     'BufferedIOBase',
  51.     'BufferedReader',
  52.     'BufferedWriter',
  53.     'BufferedRWPair',
  54.     'BufferedRandom',
  55.     'TextIOBase',
  56.     'TextIOWrapper']
  57. import os
  58. import abc
  59. import codecs
  60. import _fileio
  61. import threading
  62. DEFAULT_BUFFER_SIZE = 8 * 1024
  63. __metaclass__ = type
  64.  
  65. class BlockingIOError(IOError):
  66.     '''Exception raised when I/O would block on a non-blocking I/O stream.'''
  67.     
  68.     def __init__(self, errno, strerror, characters_written = 0):
  69.         IOError.__init__(self, errno, strerror)
  70.         self.characters_written = characters_written
  71.  
  72.  
  73.  
  74. def open(file, mode = 'r', buffering = None, encoding = None, errors = None, newline = None, closefd = True):
  75.     """Open file and return a stream. If the file cannot be opened, an IOError is
  76.     raised.
  77.  
  78.     file is either a string giving the name (and the path if the file
  79.     isn't in the current working directory) of the file to be opened or an
  80.     integer file descriptor of the file to be wrapped. (If a file
  81.     descriptor is given, it is closed when the returned I/O object is
  82.     closed, unless closefd is set to False.)
  83.  
  84.     mode is an optional string that specifies the mode in which the file
  85.     is opened. It defaults to 'r' which means open for reading in text
  86.     mode.  Other common values are 'w' for writing (truncating the file if
  87.     it already exists), and 'a' for appending (which on some Unix systems,
  88.     means that all writes append to the end of the file regardless of the
  89.     current seek position). In text mode, if encoding is not specified the
  90.     encoding used is platform dependent. (For reading and writing raw
  91.     bytes use binary mode and leave encoding unspecified.) The available
  92.     modes are:
  93.  
  94.     ========= ===============================================================
  95.     Character Meaning
  96.     --------- ---------------------------------------------------------------
  97.     'r'       open for reading (default)
  98.     'w'       open for writing, truncating the file first
  99.     'a'       open for writing, appending to the end of the file if it exists
  100.     'b'       binary mode
  101.     't'       text mode (default)
  102.     '+'       open a disk file for updating (reading and writing)
  103.     'U'       universal newline mode (for backwards compatibility; unneeded
  104.               for new code)
  105.     ========= ===============================================================
  106.  
  107.     The default mode is 'rt' (open for reading text). For binary random
  108.     access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  109.     'r+b' opens the file without truncation.
  110.  
  111.     Python distinguishes between files opened in binary and text modes,
  112.     even when the underlying operating system doesn't. Files opened in
  113.     binary mode (appending 'b' to the mode argument) return contents as
  114.     bytes objects without any decoding. In text mode (the default, or when
  115.     't' is appended to the mode argument), the contents of the file are
  116.     returned as strings, the bytes having been first decoded using a
  117.     platform-dependent encoding or using the specified encoding if given.
  118.  
  119.     buffering is an optional integer used to set the buffering policy. By
  120.     default full buffering is on. Pass 0 to switch buffering off (only
  121.     allowed in binary mode), 1 to set line buffering, and an integer > 1
  122.     for full buffering.
  123.  
  124.     encoding is the name of the encoding used to decode or encode the
  125.     file. This should only be used in text mode. The default encoding is
  126.     platform dependent, but any encoding supported by Python can be
  127.     passed.  See the codecs module for the list of supported encodings.
  128.  
  129.     errors is an optional string that specifies how encoding errors are to
  130.     be handled---this argument should not be used in binary mode. Pass
  131.     'strict' to raise a ValueError exception if there is an encoding error
  132.     (the default of None has the same effect), or pass 'ignore' to ignore
  133.     errors. (Note that ignoring encoding errors can lead to data loss.)
  134.     See the documentation for codecs.register for a list of the permitted
  135.     encoding error strings.
  136.  
  137.     newline controls how universal newlines works (it only applies to text
  138.     mode). It can be None, '', '\\n', '\\r', and '\\r\\n'.  It works as
  139.     follows:
  140.  
  141.     * On input, if newline is None, universal newlines mode is
  142.       enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and
  143.       these are translated into '\\n' before being returned to the
  144.       caller. If it is '', universal newline mode is enabled, but line
  145.       endings are returned to the caller untranslated. If it has any of
  146.       the other legal values, input lines are only terminated by the given
  147.       string, and the line ending is returned to the caller untranslated.
  148.  
  149.     * On output, if newline is None, any '\\n' characters written are
  150.       translated to the system default line separator, os.linesep. If
  151.       newline is '', no translation takes place. If newline is any of the
  152.       other legal values, any '\\n' characters written are translated to
  153.       the given string.
  154.  
  155.     If closefd is False, the underlying file descriptor will be kept open
  156.     when the file is closed. This does not work when a file name is given
  157.     and must be True in that case.
  158.  
  159.     open() returns a file object whose type depends on the mode, and
  160.     through which the standard file operations such as reading and writing
  161.     are performed. When open() is used to open a file in a text mode ('w',
  162.     'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
  163.     a file in a binary mode, the returned class varies: in read binary
  164.     mode, it returns a BufferedReader; in write binary and append binary
  165.     modes, it returns a BufferedWriter, and in read/write mode, it returns
  166.     a BufferedRandom.
  167.  
  168.     It is also possible to use a string or bytearray as a file for both
  169.     reading and writing. For strings StringIO can be used like a file
  170.     opened in a text mode, and for bytes a BytesIO can be used like a file
  171.     opened in a binary mode.
  172.     """
  173.     if not isinstance(file, (basestring, int)):
  174.         raise TypeError('invalid file: %r' % file)
  175.     isinstance(file, (basestring, int))
  176.     if not isinstance(mode, basestring):
  177.         raise TypeError('invalid mode: %r' % mode)
  178.     isinstance(mode, basestring)
  179.     if buffering is not None and not isinstance(buffering, int):
  180.         raise TypeError('invalid buffering: %r' % buffering)
  181.     not isinstance(buffering, int)
  182.     if encoding is not None and not isinstance(encoding, basestring):
  183.         raise TypeError('invalid encoding: %r' % encoding)
  184.     not isinstance(encoding, basestring)
  185.     if errors is not None and not isinstance(errors, basestring):
  186.         raise TypeError('invalid errors: %r' % errors)
  187.     not isinstance(errors, basestring)
  188.     modes = set(mode)
  189.     if modes - set('arwb+tU') or len(mode) > len(modes):
  190.         raise ValueError('invalid mode: %r' % mode)
  191.     len(mode) > len(modes)
  192.     reading = 'r' in modes
  193.     writing = 'w' in modes
  194.     appending = 'a' in modes
  195.     updating = '+' in modes
  196.     text = 't' in modes
  197.     binary = 'b' in modes
  198.     if 'U' in modes:
  199.         if writing or appending:
  200.             raise ValueError("can't use U and writing mode at once")
  201.         appending
  202.         reading = True
  203.     
  204.     if text and binary:
  205.         raise ValueError("can't have text and binary mode at once")
  206.     binary
  207.     if reading + writing + appending > 1:
  208.         raise ValueError("can't have read/write/append mode at once")
  209.     reading + writing + appending > 1
  210.     if not reading and writing or appending:
  211.         raise ValueError('must have exactly one of read/write/append mode')
  212.     appending
  213.     if binary and encoding is not None:
  214.         raise ValueError("binary mode doesn't take an encoding argument")
  215.     encoding is not None
  216.     if binary and errors is not None:
  217.         raise ValueError("binary mode doesn't take an errors argument")
  218.     errors is not None
  219.     if binary and newline is not None:
  220.         raise ValueError("binary mode doesn't take a newline argument")
  221.     newline is not None
  222.     if not reading or 'r':
  223.         pass
  224.     if not writing or 'w':
  225.         pass
  226.     if not appending or 'a':
  227.         pass
  228.     if not updating or '+':
  229.         pass
  230.     raw = FileIO(file, '' + '' + '' + '', closefd)
  231.     if buffering is None:
  232.         buffering = -1
  233.     
  234.     line_buffering = False
  235.     if (buffering == 1 or buffering < 0) and raw.isatty():
  236.         buffering = -1
  237.         line_buffering = True
  238.     
  239.     if buffering < 0:
  240.         buffering = DEFAULT_BUFFER_SIZE
  241.         
  242.         try:
  243.             bs = os.fstat(raw.fileno()).st_blksize
  244.         except (os.error, AttributeError):
  245.             pass
  246.  
  247.         if bs > 1:
  248.             buffering = bs
  249.         
  250.     
  251.     if buffering < 0:
  252.         raise ValueError('invalid buffering size')
  253.     buffering < 0
  254.     if buffering == 0:
  255.         if binary:
  256.             return raw
  257.         raise ValueError("can't have unbuffered text I/O")
  258.     buffering == 0
  259.     if updating:
  260.         buffer = BufferedRandom(raw, buffering)
  261.     elif writing or appending:
  262.         buffer = BufferedWriter(raw, buffering)
  263.     elif reading:
  264.         buffer = BufferedReader(raw, buffering)
  265.     else:
  266.         raise ValueError('unknown mode: %r' % mode)
  267.     if appending:
  268.         return buffer
  269.     text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
  270.     text.mode = mode
  271.     return text
  272.  
  273.  
  274. class _DocDescriptor:
  275.     '''Helper for builtins.open.__doc__
  276.     '''
  277.     
  278.     def __get__(self, obj, typ):
  279.         return "open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)\n\n" + open.__doc__
  280.  
  281.  
  282.  
  283. class OpenWrapper:
  284.     """Wrapper for builtins.open
  285.  
  286.     Trick so that open won't become a bound method when stored
  287.     as a class variable (as dumbdbm does).
  288.  
  289.     See initstdio() in Python/pythonrun.c.
  290.     """
  291.     __doc__ = _DocDescriptor()
  292.     
  293.     def __new__(cls, *args, **kwargs):
  294.         return open(*args, **kwargs)
  295.  
  296.  
  297.  
  298. class UnsupportedOperation(ValueError, IOError):
  299.     pass
  300.  
  301.  
  302. class IOBase(object):
  303.     """The abstract base class for all I/O classes, acting on streams of
  304.     bytes. There is no public constructor.
  305.  
  306.     This class provides dummy implementations for many methods that
  307.     derived classes can override selectively; the default implementations
  308.     represent a file that cannot be read, written or seeked.
  309.  
  310.     Even though IOBase does not declare read, readinto, or write because
  311.     their signatures will vary, implementations and clients should
  312.     consider those methods part of the interface. Also, implementations
  313.     may raise a IOError when operations they do not support are called.
  314.  
  315.     The basic type used for binary data read from or written to a file is
  316.     bytes. bytearrays are accepted too, and in some cases (such as
  317.     readinto) needed. Text I/O classes work with str data.
  318.  
  319.     Note that calling any method (even inquiries) on a closed stream is
  320.     undefined. Implementations may raise IOError in this case.
  321.  
  322.     IOBase (and its subclasses) support the iterator protocol, meaning
  323.     that an IOBase object can be iterated over yielding the lines in a
  324.     stream.
  325.  
  326.     IOBase also supports the :keyword:`with` statement. In this example,
  327.     fp is closed after the suite of the with statment is complete:
  328.  
  329.     with open('spam.txt', 'r') as fp:
  330.         fp.write('Spam and eggs!')
  331.     """
  332.     __metaclass__ = abc.ABCMeta
  333.     
  334.     def _unsupported(self, name):
  335.         '''Internal: raise an exception for unsupported operations.'''
  336.         raise UnsupportedOperation('%s.%s() not supported' % (self.__class__.__name__, name))
  337.  
  338.     
  339.     def seek(self, pos, whence = 0):
  340.         '''Change stream position.
  341.  
  342.         Change the stream position to byte offset offset. offset is
  343.         interpreted relative to the position indicated by whence.  Values
  344.         for whence are:
  345.  
  346.         * 0 -- start of stream (the default); offset should be zero or positive
  347.         * 1 -- current stream position; offset may be negative
  348.         * 2 -- end of stream; offset is usually negative
  349.  
  350.         Return the new absolute position.
  351.         '''
  352.         self._unsupported('seek')
  353.  
  354.     
  355.     def tell(self):
  356.         '''Return current stream position.'''
  357.         return self.seek(0, 1)
  358.  
  359.     
  360.     def truncate(self, pos = None):
  361.         '''Truncate file to size bytes.
  362.  
  363.         Size defaults to the current IO position as reported by tell().  Return
  364.         the new size.
  365.         '''
  366.         self._unsupported('truncate')
  367.  
  368.     
  369.     def flush(self):
  370.         '''Flush write buffers, if applicable.
  371.  
  372.         This is not implemented for read-only and non-blocking streams.
  373.         '''
  374.         pass
  375.  
  376.     __closed = False
  377.     
  378.     def close(self):
  379.         '''Flush and close the IO object.
  380.  
  381.         This method has no effect if the file is already closed.
  382.         '''
  383.         if not self._IOBase__closed:
  384.             
  385.             try:
  386.                 self.flush()
  387.             except IOError:
  388.                 pass
  389.  
  390.             self._IOBase__closed = True
  391.         
  392.  
  393.     
  394.     def __del__(self):
  395.         '''Destructor.  Calls close().'''
  396.         
  397.         try:
  398.             self.close()
  399.         except:
  400.             pass
  401.  
  402.  
  403.     
  404.     def seekable(self):
  405.         '''Return whether object supports random access.
  406.  
  407.         If False, seek(), tell() and truncate() will raise IOError.
  408.         This method may need to do a test seek().
  409.         '''
  410.         return False
  411.  
  412.     
  413.     def _checkSeekable(self, msg = None):
  414.         '''Internal: raise an IOError if file is not seekable
  415.         '''
  416.         if not self.seekable():
  417.             raise None(IOError if msg is None else msg)
  418.         self.seekable()
  419.  
  420.     
  421.     def readable(self):
  422.         '''Return whether object was opened for reading.
  423.  
  424.         If False, read() will raise IOError.
  425.         '''
  426.         return False
  427.  
  428.     
  429.     def _checkReadable(self, msg = None):
  430.         '''Internal: raise an IOError if file is not readable
  431.         '''
  432.         if not self.readable():
  433.             raise None(IOError if msg is None else msg)
  434.         self.readable()
  435.  
  436.     
  437.     def writable(self):
  438.         '''Return whether object was opened for writing.
  439.  
  440.         If False, write() and truncate() will raise IOError.
  441.         '''
  442.         return False
  443.  
  444.     
  445.     def _checkWritable(self, msg = None):
  446.         '''Internal: raise an IOError if file is not writable
  447.         '''
  448.         if not self.writable():
  449.             raise None(IOError if msg is None else msg)
  450.         self.writable()
  451.  
  452.     
  453.     def closed(self):
  454.         '''closed: bool.  True iff the file has been closed.
  455.  
  456.         For backwards compatibility, this is a property, not a predicate.
  457.         '''
  458.         return self._IOBase__closed
  459.  
  460.     closed = property(closed)
  461.     
  462.     def _checkClosed(self, msg = None):
  463.         '''Internal: raise an ValueError if file is closed
  464.         '''
  465.         if self.closed:
  466.             raise None(ValueError if msg is None else msg)
  467.         self.closed
  468.  
  469.     
  470.     def __enter__(self):
  471.         '''Context management protocol.  Returns self.'''
  472.         self._checkClosed()
  473.         return self
  474.  
  475.     
  476.     def __exit__(self, *args):
  477.         '''Context management protocol.  Calls close()'''
  478.         self.close()
  479.  
  480.     
  481.     def fileno(self):
  482.         '''Returns underlying file descriptor if one exists.
  483.  
  484.         An IOError is raised if the IO object does not use a file descriptor.
  485.         '''
  486.         self._unsupported('fileno')
  487.  
  488.     
  489.     def isatty(self):
  490.         """Return whether this is an 'interactive' stream.
  491.  
  492.         Return False if it can't be determined.
  493.         """
  494.         self._checkClosed()
  495.         return False
  496.  
  497.     
  498.     def readline(self, limit = -1):
  499.         """Read and return a line from the stream.
  500.  
  501.         If limit is specified, at most limit bytes will be read.
  502.  
  503.         The line terminator is always b'\\n' for binary files; for text
  504.         files, the newlines argument to open can be used to select the line
  505.         terminator(s) recognized.
  506.         """
  507.         self._checkClosed()
  508.         if hasattr(self, 'peek'):
  509.             
  510.             def nreadahead():
  511.                 readahead = self.peek(1)
  512.                 if not readahead:
  513.                     return 1
  514.                 if not readahead.find(b'\n') + 1:
  515.                     pass
  516.                 n = len(readahead)
  517.                 if limit >= 0:
  518.                     n = min(n, limit)
  519.                 
  520.                 return n
  521.  
  522.         else:
  523.             
  524.             def nreadahead():
  525.                 return 1
  526.  
  527.         if limit is None:
  528.             limit = -1
  529.         
  530.         if not isinstance(limit, (int, long)):
  531.             raise TypeError('limit must be an integer')
  532.         isinstance(limit, (int, long))
  533.         res = bytearray()
  534.         while limit < 0 or len(res) < limit:
  535.             b = self.read(nreadahead())
  536.             if not b:
  537.                 break
  538.             
  539.             res += b
  540.             if res.endswith(b'\n'):
  541.                 break
  542.                 continue
  543.         return bytes(res)
  544.  
  545.     
  546.     def __iter__(self):
  547.         self._checkClosed()
  548.         return self
  549.  
  550.     
  551.     def next(self):
  552.         line = self.readline()
  553.         if not line:
  554.             raise StopIteration
  555.         line
  556.         return line
  557.  
  558.     
  559.     def readlines(self, hint = None):
  560.         '''Return a list of lines from the stream.
  561.  
  562.         hint can be specified to control the number of lines read: no more
  563.         lines will be read if the total size (in bytes/characters) of all
  564.         lines so far exceeds hint.
  565.         '''
  566.         if hint is None:
  567.             hint = -1
  568.         
  569.         if not isinstance(hint, (int, long)):
  570.             raise TypeError('hint must be an integer')
  571.         isinstance(hint, (int, long))
  572.         if hint <= 0:
  573.             return list(self)
  574.         n = 0
  575.         lines = []
  576.         for line in self:
  577.             lines.append(line)
  578.             n += len(line)
  579.             if n >= hint:
  580.                 break
  581.                 continue
  582.             hint <= 0
  583.         
  584.         return lines
  585.  
  586.     
  587.     def writelines(self, lines):
  588.         self._checkClosed()
  589.         for line in lines:
  590.             self.write(line)
  591.         
  592.  
  593.  
  594.  
  595. class RawIOBase(IOBase):
  596.     '''Base class for raw binary I/O.'''
  597.     
  598.     def read(self, n = -1):
  599.         '''Read and return up to n bytes.
  600.  
  601.         Returns an empty bytes array on EOF, or None if the object is
  602.         set not to block and has no data to read.
  603.         '''
  604.         if n is None:
  605.             n = -1
  606.         
  607.         if n < 0:
  608.             return self.readall()
  609.         b = bytearray(n.__index__())
  610.         n = self.readinto(b)
  611.         del b[n:]
  612.         return bytes(b)
  613.  
  614.     
  615.     def readall(self):
  616.         '''Read until EOF, using multiple read() call.'''
  617.         res = bytearray()
  618.         while True:
  619.             data = self.read(DEFAULT_BUFFER_SIZE)
  620.             if not data:
  621.                 break
  622.             
  623.             res += data
  624.         return bytes(res)
  625.  
  626.     
  627.     def readinto(self, b):
  628.         '''Read up to len(b) bytes into b.
  629.  
  630.         Returns number of bytes read (0 for EOF), or None if the object
  631.         is set not to block as has no data to read.
  632.         '''
  633.         self._unsupported('readinto')
  634.  
  635.     
  636.     def write(self, b):
  637.         '''Write the given buffer to the IO stream.
  638.  
  639.         Returns the number of bytes written, which may be less than len(b).
  640.         '''
  641.         self._unsupported('write')
  642.  
  643.  
  644.  
  645. class FileIO(_fileio._FileIO, RawIOBase):
  646.     '''Raw I/O implementation for OS files.'''
  647.     
  648.     def __init__(self, name, mode = 'r', closefd = True):
  649.         _fileio._FileIO.__init__(self, name, mode, closefd)
  650.         self._name = name
  651.  
  652.     
  653.     def close(self):
  654.         _fileio._FileIO.close(self)
  655.         RawIOBase.close(self)
  656.  
  657.     
  658.     def name(self):
  659.         return self._name
  660.  
  661.     name = property(name)
  662.  
  663.  
  664. class BufferedIOBase(IOBase):
  665.     '''Base class for buffered IO objects.
  666.  
  667.     The main difference with RawIOBase is that the read() method
  668.     supports omitting the size argument, and does not have a default
  669.     implementation that defers to readinto().
  670.  
  671.     In addition, read(), readinto() and write() may raise
  672.     BlockingIOError if the underlying raw stream is in non-blocking
  673.     mode and not ready; unlike their raw counterparts, they will never
  674.     return None.
  675.  
  676.     A typical implementation should not inherit from a RawIOBase
  677.     implementation, but wrap one.
  678.     '''
  679.     
  680.     def read(self, n = None):
  681.         """Read and return up to n bytes.
  682.  
  683.         If the argument is omitted, None, or negative, reads and
  684.         returns all data until EOF.
  685.  
  686.         If the argument is positive, and the underlying raw stream is
  687.         not 'interactive', multiple raw reads may be issued to satisfy
  688.         the byte count (unless EOF is reached first).  But for
  689.         interactive raw streams (XXX and for pipes?), at most one raw
  690.         read will be issued, and a short result does not imply that
  691.         EOF is imminent.
  692.  
  693.         Returns an empty bytes array on EOF.
  694.  
  695.         Raises BlockingIOError if the underlying raw stream has no
  696.         data at the moment.
  697.         """
  698.         self._unsupported('read')
  699.  
  700.     
  701.     def readinto(self, b):
  702.         """Read up to len(b) bytes into b.
  703.  
  704.         Like read(), this may issue multiple reads to the underlying raw
  705.         stream, unless the latter is 'interactive'.
  706.  
  707.         Returns the number of bytes read (0 for EOF).
  708.  
  709.         Raises BlockingIOError if the underlying raw stream has no
  710.         data at the moment.
  711.         """
  712.         data = self.read(len(b))
  713.         n = len(data)
  714.         
  715.         try:
  716.             b[:n] = data
  717.         except TypeError:
  718.             err = None
  719.             import array
  720.             if not isinstance(b, array.array):
  721.                 raise err
  722.             isinstance(b, array.array)
  723.             b[:n] = array.array(b'b', data)
  724.  
  725.         return n
  726.  
  727.     
  728.     def write(self, b):
  729.         '''Write the given buffer to the IO stream.
  730.  
  731.         Return the number of bytes written, which is never less than
  732.         len(b).
  733.  
  734.         Raises BlockingIOError if the buffer is full and the
  735.         underlying raw stream cannot accept more data at the moment.
  736.         '''
  737.         self._unsupported('write')
  738.  
  739.  
  740.  
  741. class _BufferedIOMixin(BufferedIOBase):
  742.     '''A mixin implementation of BufferedIOBase with an underlying raw stream.
  743.  
  744.     This passes most requests on to the underlying raw stream.  It
  745.     does *not* provide implementations of read(), readinto() or
  746.     write().
  747.     '''
  748.     
  749.     def __init__(self, raw):
  750.         self.raw = raw
  751.  
  752.     
  753.     def seek(self, pos, whence = 0):
  754.         return self.raw.seek(pos, whence)
  755.  
  756.     
  757.     def tell(self):
  758.         return self.raw.tell()
  759.  
  760.     
  761.     def truncate(self, pos = None):
  762.         self.flush()
  763.         if pos is None:
  764.             pos = self.tell()
  765.         
  766.         return self.raw.truncate(pos)
  767.  
  768.     
  769.     def flush(self):
  770.         self.raw.flush()
  771.  
  772.     
  773.     def close(self):
  774.         if not self.closed:
  775.             
  776.             try:
  777.                 self.flush()
  778.             except IOError:
  779.                 pass
  780.  
  781.             self.raw.close()
  782.         
  783.  
  784.     
  785.     def seekable(self):
  786.         return self.raw.seekable()
  787.  
  788.     
  789.     def readable(self):
  790.         return self.raw.readable()
  791.  
  792.     
  793.     def writable(self):
  794.         return self.raw.writable()
  795.  
  796.     
  797.     def closed(self):
  798.         return self.raw.closed
  799.  
  800.     closed = property(closed)
  801.     
  802.     def name(self):
  803.         return self.raw.name
  804.  
  805.     name = property(name)
  806.     
  807.     def mode(self):
  808.         return self.raw.mode
  809.  
  810.     mode = property(mode)
  811.     
  812.     def fileno(self):
  813.         return self.raw.fileno()
  814.  
  815.     
  816.     def isatty(self):
  817.         return self.raw.isatty()
  818.  
  819.  
  820.  
  821. class _BytesIO(BufferedIOBase):
  822.     '''Buffered I/O implementation using an in-memory bytes buffer.'''
  823.     
  824.     def __init__(self, initial_bytes = None):
  825.         buf = bytearray()
  826.         if initial_bytes is not None:
  827.             buf += bytearray(initial_bytes)
  828.         
  829.         self._buffer = buf
  830.         self._pos = 0
  831.  
  832.     
  833.     def getvalue(self):
  834.         '''Return the bytes value (contents) of the buffer
  835.         '''
  836.         if self.closed:
  837.             raise ValueError('getvalue on closed file')
  838.         self.closed
  839.         return bytes(self._buffer)
  840.  
  841.     
  842.     def read(self, n = None):
  843.         if self.closed:
  844.             raise ValueError('read from closed file')
  845.         self.closed
  846.         if n is None:
  847.             n = -1
  848.         
  849.         if not isinstance(n, (int, long)):
  850.             raise TypeError('argument must be an integer')
  851.         isinstance(n, (int, long))
  852.         if n < 0:
  853.             n = len(self._buffer)
  854.         
  855.         if len(self._buffer) <= self._pos:
  856.             return b''
  857.         newpos = min(len(self._buffer), self._pos + n)
  858.         b = self._buffer[self._pos:newpos]
  859.         self._pos = newpos
  860.         return bytes(b)
  861.  
  862.     
  863.     def read1(self, n):
  864.         '''this is the same as read.
  865.         '''
  866.         return self.read(n)
  867.  
  868.     
  869.     def write(self, b):
  870.         if self.closed:
  871.             raise ValueError('write to closed file')
  872.         self.closed
  873.         if isinstance(b, unicode):
  874.             raise TypeError("can't write unicode to binary stream")
  875.         isinstance(b, unicode)
  876.         n = len(b)
  877.         if n == 0:
  878.             return 0
  879.         pos = self._pos
  880.         self._buffer[pos:pos + n] = b
  881.         self._pos += n
  882.         return n
  883.  
  884.     
  885.     def seek(self, pos, whence = 0):
  886.         if self.closed:
  887.             raise ValueError('seek on closed file')
  888.         self.closed
  889.         
  890.         try:
  891.             pos = pos.__index__()
  892.         except AttributeError:
  893.             err = None
  894.             raise TypeError('an integer is required')
  895.  
  896.         if whence == 0:
  897.             if pos < 0:
  898.                 raise ValueError('negative seek position %r' % (pos,))
  899.             pos < 0
  900.             self._pos = pos
  901.         elif whence == 1:
  902.             self._pos = max(0, self._pos + pos)
  903.         elif whence == 2:
  904.             self._pos = max(0, len(self._buffer) + pos)
  905.         else:
  906.             raise ValueError('invalid whence value')
  907.         return (whence == 0)._pos
  908.  
  909.     
  910.     def tell(self):
  911.         if self.closed:
  912.             raise ValueError('tell on closed file')
  913.         self.closed
  914.         return self._pos
  915.  
  916.     
  917.     def truncate(self, pos = None):
  918.         if self.closed:
  919.             raise ValueError('truncate on closed file')
  920.         self.closed
  921.         if pos is None:
  922.             pos = self._pos
  923.         elif pos < 0:
  924.             raise ValueError('negative truncate position %r' % (pos,))
  925.         
  926.         del self._buffer[pos:]
  927.         return self.seek(pos)
  928.  
  929.     
  930.     def readable(self):
  931.         return True
  932.  
  933.     
  934.     def writable(self):
  935.         return True
  936.  
  937.     
  938.     def seekable(self):
  939.         return True
  940.  
  941.  
  942.  
  943. try:
  944.     import _bytesio
  945.     
  946.     class BytesIO(_bytesio._BytesIO, BufferedIOBase):
  947.         __doc__ = _bytesio._BytesIO.__doc__
  948.  
  949. except ImportError:
  950.     BytesIO = _BytesIO
  951.  
  952.  
  953. class BufferedReader(_BufferedIOMixin):
  954.     '''BufferedReader(raw[, buffer_size])
  955.  
  956.     A buffer for a readable, sequential BaseRawIO object.
  957.  
  958.     The constructor creates a BufferedReader for the given readable raw
  959.     stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
  960.     is used.
  961.     '''
  962.     
  963.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE):
  964.         '''Create a new buffered reader using the given readable raw IO object.
  965.         '''
  966.         raw._checkReadable()
  967.         _BufferedIOMixin.__init__(self, raw)
  968.         self.buffer_size = buffer_size
  969.         self._reset_read_buf()
  970.         self._read_lock = threading.Lock()
  971.  
  972.     
  973.     def _reset_read_buf(self):
  974.         self._read_buf = b''
  975.         self._read_pos = 0
  976.  
  977.     
  978.     def read(self, n = None):
  979.         '''Read n bytes.
  980.  
  981.         Returns exactly n bytes of data unless the underlying raw IO
  982.         stream reaches EOF or if the call would block in non-blocking
  983.         mode. If n is negative, read until EOF or until read() would
  984.         block.
  985.         '''
  986.         self._read_lock.__enter__()
  987.         
  988.         try:
  989.             return self._read_unlocked(n)
  990.         finally:
  991.             pass
  992.  
  993.  
  994.     
  995.     def _read_unlocked(self, n = None):
  996.         nodata_val = b''
  997.         empty_values = (b'', None)
  998.         buf = self._read_buf
  999.         pos = self._read_pos
  1000.         if n is None or n == -1:
  1001.             self._reset_read_buf()
  1002.             chunks = [
  1003.                 buf[pos:]]
  1004.             current_size = 0
  1005.             while True:
  1006.                 chunk = self.raw.read()
  1007.                 if chunk in empty_values:
  1008.                     nodata_val = chunk
  1009.                     break
  1010.                 
  1011.                 current_size += len(chunk)
  1012.                 chunks.append(chunk)
  1013.             if not b''.join(chunks):
  1014.                 pass
  1015.             return nodata_val
  1016.         avail = len(buf) - pos
  1017.         if n <= avail:
  1018.             self._read_pos += n
  1019.             return buf[pos:pos + n]
  1020.         chunks = [
  1021.             buf[pos:]]
  1022.         wanted = max(self.buffer_size, n)
  1023.         while avail < n:
  1024.             chunk = self.raw.read(wanted)
  1025.             avail += len(chunk)
  1026.             chunks.append(chunk)
  1027.             continue
  1028.             None if chunk in empty_values else n == -1
  1029.         n = min(n, avail)
  1030.         out = b''.join(chunks)
  1031.         self._read_buf = out[n:]
  1032.         self._read_pos = 0
  1033.         if out:
  1034.             return out[:n]
  1035.         return nodata_val
  1036.  
  1037.     
  1038.     def peek(self, n = 0):
  1039.         '''Returns buffered bytes without advancing the position.
  1040.  
  1041.         The argument indicates a desired minimal number of bytes; we
  1042.         do at most one raw read to satisfy it.  We never return more
  1043.         than self.buffer_size.
  1044.         '''
  1045.         self._read_lock.__enter__()
  1046.         
  1047.         try:
  1048.             return self._peek_unlocked(n)
  1049.         finally:
  1050.             pass
  1051.  
  1052.  
  1053.     
  1054.     def _peek_unlocked(self, n = 0):
  1055.         want = min(n, self.buffer_size)
  1056.         have = len(self._read_buf) - self._read_pos
  1057.         if have < want:
  1058.             to_read = self.buffer_size - have
  1059.             current = self.raw.read(to_read)
  1060.             if current:
  1061.                 self._read_buf = self._read_buf[self._read_pos:] + current
  1062.                 self._read_pos = 0
  1063.             
  1064.         
  1065.         return self._read_buf[self._read_pos:]
  1066.  
  1067.     
  1068.     def read1(self, n):
  1069.         '''Reads up to n bytes, with at most one read() system call.'''
  1070.         if n <= 0:
  1071.             return b''
  1072.         self._read_lock.__enter__()
  1073.         
  1074.         try:
  1075.             self._peek_unlocked(1)
  1076.             return self._read_unlocked(min(n, len(self._read_buf) - self._read_pos))
  1077.         finally:
  1078.             pass
  1079.  
  1080.  
  1081.     
  1082.     def tell(self):
  1083.         return (self.raw.tell() - len(self._read_buf)) + self._read_pos
  1084.  
  1085.     
  1086.     def seek(self, pos, whence = 0):
  1087.         self._read_lock.__enter__()
  1088.         
  1089.         try:
  1090.             pos = self.raw.seek(pos, whence)
  1091.             self._reset_read_buf()
  1092.             return pos
  1093.         finally:
  1094.             pass
  1095.  
  1096.  
  1097.  
  1098.  
  1099. class BufferedWriter(_BufferedIOMixin):
  1100.     '''A buffer for a writeable sequential RawIO object.
  1101.  
  1102.     The constructor creates a BufferedWriter for the given writeable raw
  1103.     stream. If the buffer_size is not given, it defaults to
  1104.     DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
  1105.     twice the buffer size.
  1106.     '''
  1107.     
  1108.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1109.         raw._checkWritable()
  1110.         _BufferedIOMixin.__init__(self, raw)
  1111.         self.buffer_size = buffer_size
  1112.         self.max_buffer_size = None if max_buffer_size is None else max_buffer_size
  1113.         self._write_buf = bytearray()
  1114.         self._write_lock = threading.Lock()
  1115.  
  1116.     
  1117.     def write(self, b):
  1118.         if self.closed:
  1119.             raise ValueError('write to closed file')
  1120.         self.closed
  1121.         if isinstance(b, unicode):
  1122.             raise TypeError("can't write unicode to binary stream")
  1123.         isinstance(b, unicode)
  1124.         self._write_lock.__enter__()
  1125.         
  1126.         try:
  1127.             if len(self._write_buf) > self.buffer_size:
  1128.                 
  1129.                 try:
  1130.                     self._flush_unlocked()
  1131.                 except BlockingIOError:
  1132.                     self._write_lock.__exit__
  1133.                     e = self._write_lock.__exit__
  1134.                     self._write_lock
  1135.                     raise BlockingIOError(e.errno, e.strerror, 0)
  1136.                 except:
  1137.                     self._write_lock.__exit__<EXCEPTION MATCH>BlockingIOError
  1138.                 
  1139.  
  1140.             self._write_lock.__exit__
  1141.             before = len(self._write_buf)
  1142.             self._write_buf.extend(b)
  1143.             written = len(self._write_buf) - before
  1144.             if len(self._write_buf) > self.buffer_size:
  1145.                 
  1146.                 try:
  1147.                     self._flush_unlocked()
  1148.                 except BlockingIOError:
  1149.                     self._write_lock.__exit__
  1150.                     e = self._write_lock.__exit__
  1151.                     self._write_lock
  1152.                     if len(self._write_buf) > self.max_buffer_size:
  1153.                         overage = len(self._write_buf) - self.max_buffer_size
  1154.                         self._write_buf = self._write_buf[:self.max_buffer_size]
  1155.                         raise BlockingIOError(e.errno, e.strerror, overage)
  1156.                     len(self._write_buf) > self.max_buffer_size
  1157.                 except:
  1158.                     self._write_lock.__exit__<EXCEPTION MATCH>BlockingIOError
  1159.                 
  1160.  
  1161.             self._write_lock.__exit__
  1162.             return written
  1163.         finally:
  1164.             pass
  1165.  
  1166.  
  1167.     
  1168.     def truncate(self, pos = None):
  1169.         self._write_lock.__enter__()
  1170.         
  1171.         try:
  1172.             self._flush_unlocked()
  1173.             return self.raw.truncate(pos)
  1174.         finally:
  1175.             pass
  1176.  
  1177.  
  1178.     
  1179.     def flush(self):
  1180.         self._write_lock.__enter__()
  1181.         
  1182.         try:
  1183.             self._flush_unlocked()
  1184.         finally:
  1185.             pass
  1186.  
  1187.  
  1188.     
  1189.     def _flush_unlocked(self):
  1190.         if self.closed:
  1191.             raise ValueError('flush of closed file')
  1192.         self.closed
  1193.         written = 0
  1194.         
  1195.         try:
  1196.             while self._write_buf:
  1197.                 n = self.raw.write(self._write_buf)
  1198.                 del self._write_buf[:n]
  1199.                 written += n
  1200.         except BlockingIOError:
  1201.             e = None
  1202.             n = e.characters_written
  1203.             del self._write_buf[:n]
  1204.             written += n
  1205.             raise BlockingIOError(e.errno, e.strerror, written)
  1206.  
  1207.  
  1208.     
  1209.     def tell(self):
  1210.         return self.raw.tell() + len(self._write_buf)
  1211.  
  1212.     
  1213.     def seek(self, pos, whence = 0):
  1214.         self._write_lock.__enter__()
  1215.         
  1216.         try:
  1217.             self._flush_unlocked()
  1218.             return self.raw.seek(pos, whence)
  1219.         finally:
  1220.             pass
  1221.  
  1222.  
  1223.  
  1224.  
  1225. class BufferedRWPair(BufferedIOBase):
  1226.     '''A buffered reader and writer object together.
  1227.  
  1228.     A buffered reader object and buffered writer object put together to
  1229.     form a sequential IO object that can read and write. This is typically
  1230.     used with a socket or two-way pipe.
  1231.  
  1232.     reader and writer are RawIOBase objects that are readable and
  1233.     writeable respectively. If the buffer_size is omitted it defaults to
  1234.     DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
  1235.     defaults to twice the buffer size.
  1236.     '''
  1237.     
  1238.     def __init__(self, reader, writer, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1239.         '''Constructor.
  1240.  
  1241.         The arguments are two RawIO instances.
  1242.         '''
  1243.         reader._checkReadable()
  1244.         writer._checkWritable()
  1245.         self.reader = BufferedReader(reader, buffer_size)
  1246.         self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
  1247.  
  1248.     
  1249.     def read(self, n = None):
  1250.         if n is None:
  1251.             n = -1
  1252.         
  1253.         return self.reader.read(n)
  1254.  
  1255.     
  1256.     def readinto(self, b):
  1257.         return self.reader.readinto(b)
  1258.  
  1259.     
  1260.     def write(self, b):
  1261.         return self.writer.write(b)
  1262.  
  1263.     
  1264.     def peek(self, n = 0):
  1265.         return self.reader.peek(n)
  1266.  
  1267.     
  1268.     def read1(self, n):
  1269.         return self.reader.read1(n)
  1270.  
  1271.     
  1272.     def readable(self):
  1273.         return self.reader.readable()
  1274.  
  1275.     
  1276.     def writable(self):
  1277.         return self.writer.writable()
  1278.  
  1279.     
  1280.     def flush(self):
  1281.         return self.writer.flush()
  1282.  
  1283.     
  1284.     def close(self):
  1285.         self.writer.close()
  1286.         self.reader.close()
  1287.  
  1288.     
  1289.     def isatty(self):
  1290.         if not self.reader.isatty():
  1291.             pass
  1292.         return self.writer.isatty()
  1293.  
  1294.     
  1295.     def closed(self):
  1296.         return self.writer.closed
  1297.  
  1298.     closed = property(closed)
  1299.  
  1300.  
  1301. class BufferedRandom(BufferedWriter, BufferedReader):
  1302.     '''A buffered interface to random access streams.
  1303.  
  1304.     The constructor creates a reader and writer for a seekable stream,
  1305.     raw, given in the first argument. If the buffer_size is omitted it
  1306.     defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
  1307.     writer) defaults to twice the buffer size.
  1308.     '''
  1309.     
  1310.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1311.         raw._checkSeekable()
  1312.         BufferedReader.__init__(self, raw, buffer_size)
  1313.         BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
  1314.  
  1315.     
  1316.     def seek(self, pos, whence = 0):
  1317.         self.flush()
  1318.         pos = self.raw.seek(pos, whence)
  1319.         self._read_lock.__enter__()
  1320.         
  1321.         try:
  1322.             self._reset_read_buf()
  1323.         finally:
  1324.             pass
  1325.  
  1326.         return pos
  1327.  
  1328.     
  1329.     def tell(self):
  1330.         if self._write_buf:
  1331.             return self.raw.tell() + len(self._write_buf)
  1332.         return BufferedReader.tell(self)
  1333.  
  1334.     
  1335.     def truncate(self, pos = None):
  1336.         if pos is None:
  1337.             pos = self.tell()
  1338.         
  1339.         self.seek(pos)
  1340.         return BufferedWriter.truncate(self)
  1341.  
  1342.     
  1343.     def read(self, n = None):
  1344.         if n is None:
  1345.             n = -1
  1346.         
  1347.         self.flush()
  1348.         return BufferedReader.read(self, n)
  1349.  
  1350.     
  1351.     def readinto(self, b):
  1352.         self.flush()
  1353.         return BufferedReader.readinto(self, b)
  1354.  
  1355.     
  1356.     def peek(self, n = 0):
  1357.         self.flush()
  1358.         return BufferedReader.peek(self, n)
  1359.  
  1360.     
  1361.     def read1(self, n):
  1362.         self.flush()
  1363.         return BufferedReader.read1(self, n)
  1364.  
  1365.     
  1366.     def write(self, b):
  1367.         return BufferedWriter.write(self, b)
  1368.  
  1369.  
  1370.  
  1371. class TextIOBase(IOBase):
  1372.     """Base class for text I/O.
  1373.  
  1374.     This class provides a character and line based interface to stream
  1375.     I/O. There is no readinto method because Python's character strings
  1376.     are immutable. There is no public constructor.
  1377.     """
  1378.     
  1379.     def read(self, n = -1):
  1380.         '''Read at most n characters from stream.
  1381.  
  1382.         Read from underlying buffer until we have n characters or we hit EOF.
  1383.         If n is negative or omitted, read until EOF.
  1384.         '''
  1385.         self._unsupported('read')
  1386.  
  1387.     
  1388.     def write(self, s):
  1389.         '''Write string s to stream.'''
  1390.         self._unsupported('write')
  1391.  
  1392.     
  1393.     def truncate(self, pos = None):
  1394.         '''Truncate size to pos.'''
  1395.         self._unsupported('truncate')
  1396.  
  1397.     
  1398.     def readline(self):
  1399.         '''Read until newline or EOF.
  1400.  
  1401.         Returns an empty string if EOF is hit immediately.
  1402.         '''
  1403.         self._unsupported('readline')
  1404.  
  1405.     
  1406.     def encoding(self):
  1407.         '''Subclasses should override.'''
  1408.         pass
  1409.  
  1410.     encoding = property(encoding)
  1411.     
  1412.     def newlines(self):
  1413.         '''Line endings translated so far.
  1414.  
  1415.         Only line endings translated during reading are considered.
  1416.  
  1417.         Subclasses should override.
  1418.         '''
  1419.         pass
  1420.  
  1421.     newlines = property(newlines)
  1422.  
  1423.  
  1424. class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
  1425.     '''Codec used when reading a file in universal newlines mode.
  1426.     It wraps another incremental decoder, translating \\r\\n and \\r into \\n.
  1427.     It also records the types of newlines encountered.
  1428.     When used with translate=False, it ensures that the newline sequence is
  1429.     returned in one piece.
  1430.     '''
  1431.     
  1432.     def __init__(self, decoder, translate, errors = 'strict'):
  1433.         codecs.IncrementalDecoder.__init__(self, errors = errors)
  1434.         self.translate = translate
  1435.         self.decoder = decoder
  1436.         self.seennl = 0
  1437.         self.pendingcr = False
  1438.  
  1439.     
  1440.     def decode(self, input, final = False):
  1441.         output = self.decoder.decode(input, final = final)
  1442.         if self.pendingcr:
  1443.             if output or final:
  1444.                 output = '\r' + output
  1445.                 self.pendingcr = False
  1446.             
  1447.         if output.endswith('\r') and not final:
  1448.             output = output[:-1]
  1449.             self.pendingcr = True
  1450.         
  1451.         crlf = output.count('\r\n')
  1452.         cr = output.count('\r') - crlf
  1453.         lf = output.count('\n') - crlf
  1454.         if lf:
  1455.             pass
  1456.         if cr:
  1457.             pass
  1458.         if crlf:
  1459.             pass
  1460.         self.seennl |= self._LF | self._CR | self._CRLF
  1461.         if self.translate:
  1462.             if crlf:
  1463.                 output = output.replace('\r\n', '\n')
  1464.             
  1465.             if cr:
  1466.                 output = output.replace('\r', '\n')
  1467.             
  1468.         
  1469.         return output
  1470.  
  1471.     
  1472.     def getstate(self):
  1473.         (buf, flag) = self.decoder.getstate()
  1474.         flag <<= 1
  1475.         if self.pendingcr:
  1476.             flag |= 1
  1477.         
  1478.         return (buf, flag)
  1479.  
  1480.     
  1481.     def setstate(self, state):
  1482.         (buf, flag) = state
  1483.         self.pendingcr = bool(flag & 1)
  1484.         self.decoder.setstate((buf, flag >> 1))
  1485.  
  1486.     
  1487.     def reset(self):
  1488.         self.seennl = 0
  1489.         self.pendingcr = False
  1490.         self.decoder.reset()
  1491.  
  1492.     _LF = 1
  1493.     _CR = 2
  1494.     _CRLF = 4
  1495.     
  1496.     def newlines(self):
  1497.         return (None, '\n', '\r', ('\r', '\n'), '\r\n', ('\n', '\r\n'), ('\r', '\r\n'), ('\r', '\n', '\r\n'))[self.seennl]
  1498.  
  1499.     newlines = property(newlines)
  1500.  
  1501.  
  1502. class TextIOWrapper(TextIOBase):
  1503.     '''Character and line based layer over a BufferedIOBase object, buffer.
  1504.  
  1505.     encoding gives the name of the encoding that the stream will be
  1506.     decoded or encoded with. It defaults to locale.getpreferredencoding.
  1507.  
  1508.     errors determines the strictness of encoding and decoding (see the
  1509.     codecs.register) and defaults to "strict".
  1510.  
  1511.     newline can be None, \'\', \'\\n\', \'\\r\', or \'\\r\\n\'.  It controls the
  1512.     handling of line endings. If it is None, universal newlines is
  1513.     enabled.  With this enabled, on input, the lines endings \'\\n\', \'\\r\',
  1514.     or \'\\r\\n\' are translated to \'\\n\' before being returned to the
  1515.     caller. Conversely, on output, \'\\n\' is translated to the system
  1516.     default line separator, os.linesep. If newline is any other of its
  1517.     legal values, that newline becomes the newline when the file is read
  1518.     and it is returned untranslated. On output, \'\\n\' is converted to the
  1519.     newline.
  1520.  
  1521.     If line_buffering is True, a call to flush is implied when a call to
  1522.     write contains a newline character.
  1523.     '''
  1524.     _CHUNK_SIZE = 128
  1525.     
  1526.     def __init__(self, buffer, encoding = None, errors = None, newline = None, line_buffering = False):
  1527.         if newline not in (None, '', '\n', '\r', '\r\n'):
  1528.             raise ValueError('illegal newline value: %r' % (newline,))
  1529.         newline not in (None, '', '\n', '\r', '\r\n')
  1530.         if encoding is None:
  1531.             
  1532.             try:
  1533.                 encoding = os.device_encoding(buffer.fileno())
  1534.             except (AttributeError, UnsupportedOperation):
  1535.                 pass
  1536.  
  1537.             if encoding is None:
  1538.                 
  1539.                 try:
  1540.                     import locale
  1541.                 except ImportError:
  1542.                     encoding = 'ascii'
  1543.  
  1544.                 encoding = locale.getpreferredencoding()
  1545.             
  1546.         
  1547.         if not isinstance(encoding, basestring):
  1548.             raise ValueError('invalid encoding: %r' % encoding)
  1549.         isinstance(encoding, basestring)
  1550.         if errors is None:
  1551.             errors = 'strict'
  1552.         elif not isinstance(errors, basestring):
  1553.             raise ValueError('invalid errors: %r' % errors)
  1554.         
  1555.         self.buffer = buffer
  1556.         self._line_buffering = line_buffering
  1557.         self._encoding = encoding
  1558.         self._errors = errors
  1559.         self._readuniversal = not newline
  1560.         self._readtranslate = newline is None
  1561.         self._readnl = newline
  1562.         self._writetranslate = newline != ''
  1563.         if not newline:
  1564.             pass
  1565.         self._writenl = os.linesep
  1566.         self._encoder = None
  1567.         self._decoder = None
  1568.         self._decoded_chars = ''
  1569.         self._decoded_chars_used = 0
  1570.         self._snapshot = None
  1571.         self._seekable = self._telling = self.buffer.seekable()
  1572.  
  1573.     
  1574.     def encoding(self):
  1575.         return self._encoding
  1576.  
  1577.     encoding = property(encoding)
  1578.     
  1579.     def errors(self):
  1580.         return self._errors
  1581.  
  1582.     errors = property(errors)
  1583.     
  1584.     def line_buffering(self):
  1585.         return self._line_buffering
  1586.  
  1587.     line_buffering = property(line_buffering)
  1588.     
  1589.     def seekable(self):
  1590.         return self._seekable
  1591.  
  1592.     
  1593.     def readable(self):
  1594.         return self.buffer.readable()
  1595.  
  1596.     
  1597.     def writable(self):
  1598.         return self.buffer.writable()
  1599.  
  1600.     
  1601.     def flush(self):
  1602.         self.buffer.flush()
  1603.         self._telling = self._seekable
  1604.  
  1605.     
  1606.     def close(self):
  1607.         
  1608.         try:
  1609.             self.flush()
  1610.         except:
  1611.             pass
  1612.  
  1613.         self.buffer.close()
  1614.  
  1615.     
  1616.     def closed(self):
  1617.         return self.buffer.closed
  1618.  
  1619.     closed = property(closed)
  1620.     
  1621.     def name(self):
  1622.         return self.buffer.name
  1623.  
  1624.     name = property(name)
  1625.     
  1626.     def fileno(self):
  1627.         return self.buffer.fileno()
  1628.  
  1629.     
  1630.     def isatty(self):
  1631.         return self.buffer.isatty()
  1632.  
  1633.     
  1634.     def write(self, s):
  1635.         if self.closed:
  1636.             raise ValueError('write to closed file')
  1637.         self.closed
  1638.         if not isinstance(s, unicode):
  1639.             raise TypeError("can't write %s to text stream" % s.__class__.__name__)
  1640.         isinstance(s, unicode)
  1641.         length = len(s)
  1642.         if self._writetranslate or self._line_buffering:
  1643.             pass
  1644.         haslf = '\n' in s
  1645.         if haslf and self._writetranslate and self._writenl != '\n':
  1646.             s = s.replace('\n', self._writenl)
  1647.         
  1648.         if not self._encoder:
  1649.             pass
  1650.         encoder = self._get_encoder()
  1651.         b = encoder.encode(s)
  1652.         self.buffer.write(b)
  1653.         if self._line_buffering:
  1654.             if haslf or '\r' in s:
  1655.                 self.flush()
  1656.             
  1657.         self._snapshot = None
  1658.         if self._decoder:
  1659.             self._decoder.reset()
  1660.         
  1661.         return length
  1662.  
  1663.     
  1664.     def _get_encoder(self):
  1665.         make_encoder = codecs.getincrementalencoder(self._encoding)
  1666.         self._encoder = make_encoder(self._errors)
  1667.         return self._encoder
  1668.  
  1669.     
  1670.     def _get_decoder(self):
  1671.         make_decoder = codecs.getincrementaldecoder(self._encoding)
  1672.         decoder = make_decoder(self._errors)
  1673.         if self._readuniversal:
  1674.             decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
  1675.         
  1676.         self._decoder = decoder
  1677.         return decoder
  1678.  
  1679.     
  1680.     def _set_decoded_chars(self, chars):
  1681.         '''Set the _decoded_chars buffer.'''
  1682.         self._decoded_chars = chars
  1683.         self._decoded_chars_used = 0
  1684.  
  1685.     
  1686.     def _get_decoded_chars(self, n = None):
  1687.         '''Advance into the _decoded_chars buffer.'''
  1688.         offset = self._decoded_chars_used
  1689.         if n is None:
  1690.             chars = self._decoded_chars[offset:]
  1691.         else:
  1692.             chars = self._decoded_chars[offset:offset + n]
  1693.         self._decoded_chars_used += len(chars)
  1694.         return chars
  1695.  
  1696.     
  1697.     def _rewind_decoded_chars(self, n):
  1698.         '''Rewind the _decoded_chars buffer.'''
  1699.         if self._decoded_chars_used < n:
  1700.             raise AssertionError('rewind decoded_chars out of bounds')
  1701.         self._decoded_chars_used < n
  1702.         self._decoded_chars_used -= n
  1703.  
  1704.     
  1705.     def _read_chunk(self):
  1706.         '''
  1707.         Read and decode the next chunk of data from the BufferedReader.
  1708.  
  1709.         The return value is True unless EOF was reached.  The decoded string
  1710.         is placed in self._decoded_chars (replacing its previous value).
  1711.         The entire input chunk is sent to the decoder, though some of it
  1712.         may remain buffered in the decoder, yet to be converted.
  1713.         '''
  1714.         if self._decoder is None:
  1715.             raise ValueError('no decoder')
  1716.         self._decoder is None
  1717.         if self._telling:
  1718.             (dec_buffer, dec_flags) = self._decoder.getstate()
  1719.         
  1720.         input_chunk = self.buffer.read1(self._CHUNK_SIZE)
  1721.         eof = not input_chunk
  1722.         self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
  1723.         if self._telling:
  1724.             self._snapshot = (dec_flags, dec_buffer + input_chunk)
  1725.         
  1726.         return not eof
  1727.  
  1728.     
  1729.     def _pack_cookie(self, position, dec_flags = 0, bytes_to_feed = 0, need_eof = 0, chars_to_skip = 0):
  1730.         return position | dec_flags << 64 | bytes_to_feed << 128 | chars_to_skip << 192 | bool(need_eof) << 256
  1731.  
  1732.     
  1733.     def _unpack_cookie(self, bigint):
  1734.         (rest, position) = divmod(bigint, 0x10000000000000000L)
  1735.         (rest, dec_flags) = divmod(rest, 0x10000000000000000L)
  1736.         (rest, bytes_to_feed) = divmod(rest, 0x10000000000000000L)
  1737.         (need_eof, chars_to_skip) = divmod(rest, 0x10000000000000000L)
  1738.         return (position, dec_flags, bytes_to_feed, need_eof, chars_to_skip)
  1739.  
  1740.     
  1741.     def tell(self):
  1742.         if not self._seekable:
  1743.             raise IOError('underlying stream is not seekable')
  1744.         self._seekable
  1745.         if not self._telling:
  1746.             raise IOError('telling position disabled by next() call')
  1747.         self._telling
  1748.         self.flush()
  1749.         position = self.buffer.tell()
  1750.         decoder = self._decoder
  1751.         if decoder is None or self._snapshot is None:
  1752.             if self._decoded_chars:
  1753.                 raise AssertionError('pending decoded text')
  1754.             self._decoded_chars
  1755.             return position
  1756.         (dec_flags, next_input) = self._snapshot
  1757.         position -= len(next_input)
  1758.         chars_to_skip = self._decoded_chars_used
  1759.         if chars_to_skip == 0:
  1760.             return self._pack_cookie(position, dec_flags)
  1761.         saved_state = decoder.getstate()
  1762.         
  1763.         try:
  1764.             decoder.setstate((b'', dec_flags))
  1765.             start_pos = position
  1766.             start_flags = dec_flags
  1767.             bytes_fed = 0
  1768.             chars_decoded = 0
  1769.             need_eof = 0
  1770.             for next_byte in next_input:
  1771.                 bytes_fed += 1
  1772.                 chars_decoded += len(decoder.decode(next_byte))
  1773.                 (dec_buffer, dec_flags) = decoder.getstate()
  1774.                 if chars_decoded >= chars_to_skip:
  1775.                     break
  1776.                     continue
  1777.                 None if not dec_buffer and chars_decoded <= chars_to_skip else self._snapshot is None
  1778.             else:
  1779.                 chars_decoded += len(decoder.decode(b'', final = True))
  1780.                 need_eof = 1
  1781.                 if chars_decoded < chars_to_skip:
  1782.                     raise IOError("can't reconstruct logical file position")
  1783.             return self._pack_cookie(start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
  1784.         finally:
  1785.             decoder.setstate(saved_state)
  1786.  
  1787.  
  1788.     
  1789.     def truncate(self, pos = None):
  1790.         self.flush()
  1791.         if pos is None:
  1792.             pos = self.tell()
  1793.         
  1794.         self.seek(pos)
  1795.         return self.buffer.truncate()
  1796.  
  1797.     
  1798.     def seek(self, cookie, whence = 0):
  1799.         if self.closed:
  1800.             raise ValueError('tell on closed file')
  1801.         self.closed
  1802.         if not self._seekable:
  1803.             raise IOError('underlying stream is not seekable')
  1804.         self._seekable
  1805.         if whence == 1:
  1806.             if cookie != 0:
  1807.                 raise IOError("can't do nonzero cur-relative seeks")
  1808.             cookie != 0
  1809.             whence = 0
  1810.             cookie = self.tell()
  1811.         
  1812.         if whence == 2:
  1813.             if cookie != 0:
  1814.                 raise IOError("can't do nonzero end-relative seeks")
  1815.             cookie != 0
  1816.             self.flush()
  1817.             position = self.buffer.seek(0, 2)
  1818.             self._set_decoded_chars('')
  1819.             self._snapshot = None
  1820.             if self._decoder:
  1821.                 self._decoder.reset()
  1822.             
  1823.             return position
  1824.         if whence != 0:
  1825.             raise ValueError('invalid whence (%r, should be 0, 1 or 2)' % (whence,))
  1826.         whence != 0
  1827.         if cookie < 0:
  1828.             raise ValueError('negative seek position %r' % (cookie,))
  1829.         cookie < 0
  1830.         self.flush()
  1831.         (start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip) = self._unpack_cookie(cookie)
  1832.         self.buffer.seek(start_pos)
  1833.         self._set_decoded_chars('')
  1834.         self._snapshot = None
  1835.         if self._decoder and dec_flags or chars_to_skip:
  1836.             if not self._decoder:
  1837.                 pass
  1838.             self._decoder = self._get_decoder()
  1839.             self._decoder.setstate((b'', dec_flags))
  1840.             self._snapshot = (dec_flags, b'')
  1841.         
  1842.         if chars_to_skip:
  1843.             input_chunk = self.buffer.read(bytes_to_feed)
  1844.             self._set_decoded_chars(self._decoder.decode(input_chunk, need_eof))
  1845.             self._snapshot = (dec_flags, input_chunk)
  1846.             if len(self._decoded_chars) < chars_to_skip:
  1847.                 raise IOError("can't restore logical file position")
  1848.             len(self._decoded_chars) < chars_to_skip
  1849.             self._decoded_chars_used = chars_to_skip
  1850.         
  1851.         return cookie
  1852.  
  1853.     
  1854.     def read(self, n = None):
  1855.         if n is None:
  1856.             n = -1
  1857.         
  1858.         if not self._decoder:
  1859.             pass
  1860.         decoder = self._get_decoder()
  1861.         if n < 0:
  1862.             result = self._get_decoded_chars() + decoder.decode(self.buffer.read(), final = True)
  1863.             self._set_decoded_chars('')
  1864.             self._snapshot = None
  1865.             return result
  1866.         eof = False
  1867.         result = self._get_decoded_chars(n)
  1868.         while len(result) < n and not eof:
  1869.             eof = not self._read_chunk()
  1870.             result += self._get_decoded_chars(n - len(result))
  1871.             continue
  1872.             n < 0
  1873.         return result
  1874.  
  1875.     
  1876.     def next(self):
  1877.         self._telling = False
  1878.         line = self.readline()
  1879.         if not line:
  1880.             self._snapshot = None
  1881.             self._telling = self._seekable
  1882.             raise StopIteration
  1883.         line
  1884.         return line
  1885.  
  1886.     
  1887.     def readline(self, limit = None):
  1888.         if self.closed:
  1889.             raise ValueError('read from closed file')
  1890.         self.closed
  1891.         if limit is None:
  1892.             limit = -1
  1893.         
  1894.         if not isinstance(limit, (int, long)):
  1895.             raise TypeError('limit must be an integer')
  1896.         isinstance(limit, (int, long))
  1897.         line = self._get_decoded_chars()
  1898.         start = 0
  1899.         if not self._decoder:
  1900.             pass
  1901.         decoder = self._get_decoder()
  1902.         pos = None
  1903.         endpos = None
  1904.         while True:
  1905.             if self._readtranslate:
  1906.                 pos = line.find('\n', start)
  1907.                 if pos >= 0:
  1908.                     endpos = pos + 1
  1909.                     break
  1910.                 else:
  1911.                     start = len(line)
  1912.             elif self._readuniversal:
  1913.                 nlpos = line.find('\n', start)
  1914.                 crpos = line.find('\r', start)
  1915.                 if crpos == -1:
  1916.                     if nlpos == -1:
  1917.                         start = len(line)
  1918.                     else:
  1919.                         endpos = nlpos + 1
  1920.                         break
  1921.                 elif nlpos == -1:
  1922.                     endpos = crpos + 1
  1923.                     break
  1924.                 elif nlpos < crpos:
  1925.                     endpos = nlpos + 1
  1926.                     break
  1927.                 elif nlpos == crpos + 1:
  1928.                     endpos = crpos + 2
  1929.                     break
  1930.                 else:
  1931.                     endpos = crpos + 1
  1932.                     break
  1933.             else:
  1934.                 pos = line.find(self._readnl)
  1935.                 if pos >= 0:
  1936.                     endpos = pos + len(self._readnl)
  1937.                     break
  1938.                 
  1939.             if limit >= 0 and len(line) >= limit:
  1940.                 endpos = limit
  1941.                 break
  1942.             
  1943.             more_line = ''
  1944.             while self._read_chunk():
  1945.                 if self._decoded_chars:
  1946.                     break
  1947.                     continue
  1948.             if self._decoded_chars:
  1949.                 line += self._get_decoded_chars()
  1950.                 continue
  1951.             self._set_decoded_chars('')
  1952.             self._snapshot = None
  1953.             return line
  1954.         if limit >= 0 and endpos > limit:
  1955.             endpos = limit
  1956.         
  1957.         self._rewind_decoded_chars(len(line) - endpos)
  1958.         return line[:endpos]
  1959.  
  1960.     
  1961.     def newlines(self):
  1962.         if self._decoder:
  1963.             return self._decoder.newlines
  1964.  
  1965.     newlines = property(newlines)
  1966.  
  1967.  
  1968. class StringIO(TextIOWrapper):
  1969.     """An in-memory stream for text. The initial_value argument sets the
  1970.     value of object. The other arguments are like those of TextIOWrapper's
  1971.     constructor.
  1972.     """
  1973.     
  1974.     def __init__(self, initial_value = '', encoding = 'utf-8', errors = 'strict', newline = '\n'):
  1975.         super(StringIO, self).__init__(BytesIO(), encoding = encoding, errors = errors, newline = newline)
  1976.         if newline is None:
  1977.             self._writetranslate = False
  1978.         
  1979.         if initial_value:
  1980.             if not isinstance(initial_value, unicode):
  1981.                 initial_value = unicode(initial_value)
  1982.             
  1983.             self.write(initial_value)
  1984.             self.seek(0)
  1985.         
  1986.  
  1987.     
  1988.     def getvalue(self):
  1989.         self.flush()
  1990.         return self.buffer.getvalue().decode(self._encoding, self._errors)
  1991.  
  1992.  
  1993.